<template>
  <section>
    <div style="display: flex;">
      <el-input
        :placeholder="placeholder"
        v-model="userNames"
        :class="className"
        v-if="!isHiddenInput"
        :disabled="true"
      >
      </el-input>
      <el-button :size="size" :icon="icon" :disabled="disabled" :type="type" :loading="loading" @click="showUserDialog">{{
        btnLabel
        }}
      </el-button>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      custom-class="user_select_dialog"
      :title="title"
      append-to-body
      :width="width"
      ref="user_select_dialog"
      :visible.sync="sortDialogVisible"
      v-if="sortDialogVisible"
      destroy-on-close
    >
      <el-row :gutter="10">
        <el-col>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane :label="tabConfigData.showAllOrganizeName" name="all"
                         v-if="tabConfigData.showAllOrganize">


            </el-tab-pane>
            <el-tab-pane :label="tabConfigData.showCustomOrganizeName" name="custom"
                         v-if="tabConfigData.showCustomOrganize"></el-tab-pane>
            <el-tab-pane :label="tabConfigData.showAllWorkGroupName" name="workGroup"
                         v-if="tabConfigData.showAllWorkGroup"></el-tab-pane>
            <el-tab-pane :label="tabConfigData.showPersonalWorkGroupName" name="myWorkGroup"
                         v-if="tabConfigData.showPersonalWorkGroup"></el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="10" style="min-width: 300px;">
          <el-form inline>
            <el-input placeholder="请输入内容" v-model="searchCondition.keyword" clearable @input="searchUser">
              <!--              <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>-->
            </el-input>
          </el-form>
          <div class="border_node_btn" style="height:480px;margin-top: 10px;">
            <el-tree
              :show-checkbox="isMulSelect"
              node-key="id"
              ref="tree_all"
              key="tree_all"
              class="left_tree"
              :filter-node-method="filterNode"
              highlight-current
              lazy
              :load="loadNode"
              v-if="searchCondition.keyword===''&&activeName==='all'"
              :expand-on-click-node=false
              :default-expanded-keys="leftDefaultExpandKeys"
              @node-expand="leftTreeNodeExpand"
              @node-collapse="leftTreeNodeCollapse"
              @node-click="nodeClick"
              @check-change="leftCheckChange"
              :props="defaultProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span><span
                v-show="data.type==='org'">({{data.userCount}}人)</span>
              </span>
            </el-tree>
            <el-tree
              :show-checkbox="isMulSelect"
              node-key="id"
              ref="tree_custom"
              key="tree_custom"
              class="left_tree"
              :filter-node-method="filterNode"
              highlight-current
              lazy
              :load="loadNode"
              v-if="searchCondition.keyword===''&&activeName==='custom'"
              :expand-on-click-node='false'
              :default-expanded-keys="leftDefaultExpandKeys"
              @node-expand="leftTreeNodeExpand"
              @node-collapse="leftTreeNodeCollapse"
              @node-click="nodeClick"
              @check-change="leftCheckChange"
              :props="defaultProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span><span
                v-show="data.type==='org'">({{data.userCount}}人)</span>
              </span>
            </el-tree>
            <el-tree
              :show-checkbox="isMulSelect"
              node-key="id"
              ref="tree_workGroup"
              key="tree_workGroup"
              class="left_tree"
              :filter-node-method="filterNode"
              highlight-current
              lazy
              :load="loadNode"
              v-if="searchCondition.keyword===''&&activeName==='workGroup'"
              :expand-on-click-node=false
              :default-expanded-keys="leftDefaultExpandKeys"
              @node-expand="leftTreeNodeExpand"
              @node-collapse="leftTreeNodeCollapse"
              @node-click="nodeClick"
              @check-change="leftCheckChange"
              :props="defaultProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span><span
                v-show="data.type==='org'">({{data.userCount}}人)</span>
              </span>
            </el-tree>
            <el-tree
              :show-checkbox="isMulSelect"
              node-key="id"
              ref="tree_myWorkGroup"
              key="tree_myWorkGroup"
              class="left_tree"
              :filter-node-method="filterNode"
              highlight-current
              lazy
              :load="loadNode"
              v-if="searchCondition.keyword===''&&activeName==='myWorkGroup'"
              :expand-on-click-node=false
              :default-expanded-keys="leftDefaultExpandKeys"
              @node-expand="leftTreeNodeExpand"
              @node-collapse="leftTreeNodeCollapse"
              @node-click="nodeClick"
              @check-change="leftCheckChange"
              :props="defaultProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span><span
                v-show="data.type==='org'">({{data.userCount}}人)</span>
              </span>
            </el-tree>
            <el-tree
              :show-checkbox="isMulSelect"
              node-key="id"
              ref="treeLeftSearch"
              v-show="searchCondition.keyword!==''"
              class="left_tree"
              highlight-current
              :data="searchUsers"
              :expand-on-click-node=false
              @node-click="nodeClick"
              @check-change="leftCheckChange"
              :props="defaultProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="4" style="height: 500px; max-width:65px;display: table;">
          <div class="flex_box">


            <el-button
              :type=" leftSelectNode!==null?'primary':'info'"
              @click="confirmSelectUser"
              :class=""
              style="margin-top: 10px;margin-left: 0px;"
              :disable="leftSelectNode===null"
              icon="el-icon-arrow-right"
            >
            </el-button>
            <el-button
              :type=" rightSelectNode!==null?'primary':'info'"
              style="margin-top: 10px;margin-left: 0px;"
              @click="delSelectUser"
              :disable="rightSelectNode===null"
              icon="el-icon-arrow-left"
            >
            </el-button>
            <el-button
              type="primary"
              @click="allSelect"
              v-show="isMulSelect"
              :type=" containUser===0?'primary':'info'"
              style="margin-top: 10px;margin-left: 0px;"
              icon="el-icon-caret-right"
            >
            </el-button>
            <el-button
              type="primary"
              style="margin-top: 10px;margin-left: 0px;"
              icon="el-icon-caret-left"
              :type=" rightSelectUsers.length>0?'primary':'info'"
              @click="clearSelect"
            >
            </el-button>
          </div>
        </el-col>
        <el-col :span="rightSpan" ref="rightContent" :style="rightStyle">
          <el-form inline>
            <el-input placeholder="请输入内容" v-model="rightCondition" @input="rightFilter">
              <!--              <el-button slot="append" icon="el-icon-search" @click="rightFilter"></el-button>-->
            </el-input>
          </el-form>
          <div class="border_node_btn" style=" height: 480px;margin-top: 10px;">

            <el-tree
              :data="rightSelectUsers"
              default-expand-all
              node-key="id"
              ref="rightTree"
              class="rightTree"
              highlight-current
              :filter-node-method="filterNode"
              @node-click="nodeRightClick"
              :props="defaultRightProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                  <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span>  <span
                v-if="data.type!=='org'" style="margin-left: 10px;color:#cececd ">{{data.deptName?data.deptName:data.workGroupName}}</span>
                  <span style="margin-left: 10px;color:#cececd " v-if="containUser===1&&data.type==='org'">{{data.userCount}}人</span>
              </span>
            </el-tree>
          </div>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px;" v-if="containUser===1">
        <el-col>
          <span style="font-weight: bold;font-size: 18px;">总人数：</span> <span style="font-size: 18px;color: red;">{{totalCount}}人</span>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sortDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUsers"
        >确 定</el-button
        >
      </span>
    </el-dialog>
  </section>
</template>

<script>
  import ArrayUtil from "@/libs/ArrayUtil";

  export default {
    name: "user-select",
    props: {
      value: '',
      width: {
        type: String,
        default: "50%"
      },
      disabled: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: 'primary'
      },
      size: {},
      icon: {},
      title: {
        type: String,
        default: "选择组织机构和人员"
      },
      btnLabel: {
        type: String,
        default: "选择"
      },
      placeholder: {
        type: String,
        default: "请选择"
      },
      className: {},
      // 业务编码 null 使用页面属性的配置，否则根据key查询相应的配置
      businessKey: {
        type: String,
        default: null
      },
      // 0-不包含用户,1-包含所有用户,2-包含有效用户
      containUser: {
        type: Number,
        default: 2
      },
      // 是否多选
      isMulSelect: {
        type: Boolean,
        default: false
      },
      // 是否隐藏输入框
      isHiddenInput: {
        type: Boolean,
        default: false
      },
      // 选择类型 0-部门/工作组，用户，1-用户，2-部门/工作组
      selectType: {
        type: Number,
        default: 0
      },
      // tab 配置
      tabConfig: {
        type: Object,
        default: null
      },
      // 确认调用接口方法
      funcSubmit: {
        type: Function, default: () => {
          return new Promise((resolve, reject) => {
          })
        }
      },
      // 是否自动加载
      autoLoad: {
        type: [Boolean],
        default: true
      },
      loading: {
        type: [Boolean],
        default: false
      }
    },
    data() {
      return {
        leftLazy: true,// 左侧树默认懒加载
        leftDefaultExpandKeys: [],// 左侧树-默认展开keys集合
        leftCacheDefaultExpandKeys: [],// 左侧树-默认展开keys集合 缓存
        isLoad: true,// 是否初始化加载
        userNames: "",
        origId: '',
        userIds: '',
        rightCondition: '',
        rightSpan: 10,
        defaultProps: {
          children: 'children',
          label: 'name',
          isLeaf: 'leaf'
        },
        defaultRightProps: {
          children: 'list',
          label: 'name'
        },
        activeName: 'all',
        totalCount: 0,
        sortDialogVisible: false,
        searchCondition: {
          keyword: ""
        },
        users: [],
        searchUsers: [],// 搜索结果集
        rightSelectUsers: [],// 右侧选择的用户机构列表
        leftSelectNode: null,// 左侧点击选择对象
        rightSelectNode: null,// 右侧点击选择对象
        tabConfigData: {
          "showAllOrganize": true,
          "showCustomOrganize": false,
          "customOrganizeIds": 0, //自定义部门id
          "showAllWorkGroup": false,
          "showPersonalWorkGroup": false,
          "showAllOrganizeName": "全部",//显示所有部门
          "showCustomOrganizeName": "公文传输",// 显示自定义部门
          "showAllWorkGroupName": "工作组",// 显示系统工作组
          "showPersonalWorkGroupName": "我的工作组",//显示个人工作组织
        },
        temAllUsers: [],// 懒加载All用户树缓存结构，便于遍历去重
        temCustomUsers: [],// 懒加载Custom用户树缓存结构，便于遍历去重
        temWorkGroupUsers: [],// 懒加载Custom用户树缓存结构，便于遍历去重
        temMyWorkGroupUsers: [],// 懒加载Custom用户树缓存结构，便于遍历去重
      }
    },
    // model: {
    //   prop: 'value',
    //   event: 'change'
    // },
    computed: {
      rightStyle() {
        let me = this;
        let span = 10;
        this.$nextTick(function () {
          let dialog = me.$refs.user_select_dialog.$el
          let dialogBody = dialog.getElementsByClassName('el-dialog__body')
          let bodyWidth = dialogBody[0].clientWidth
          let one = (bodyWidth / 24)
          span = (bodyWidth - (one * 10 + 90)) / one
          me.rightSpan = Math.floor(span)
          me.$refs.rightContent.$el.style.width = Math.floor(bodyWidth - (one * 10 + 65) - 20) + "px"
        })
      }
    },
    mounted() {
      this.getTabConfig();
      if (this.value) {
        if (this.value && this.value.length > 0) {
          this.userIds = this.value
          if (this.autoLoad && this.isLoad) {
            this.updateDefaultUser()
          }
        }
      }
    },
    watch: {
      rightSelectUsers: {
        handler(val) {
          this.totalCount = 0
          // console.log(val, this.totalCount)
          if (val && val.length > 0) {
            this.computeCount(val);
          }
        },
        deep: true
      },
      value: {
        handler(val) {
          // console.log(val, '默认')
          if (val && val.length > 0) {
            this.userIds = val
            if (this.isLoad) {
              this.updateDefaultUser()
            }
          }
        },
        deep: true
      },
      userIds(val){
        this.$emit('change',val)
      }
    },
    methods: {

      /**
       * 描述：懒加载数据
       * 时间： 2021/3/22
       */
      async loadNode(node, resolve) {
        // console.log(this.activeName)
        if (node.level === 0) {
          switch (this.activeName) {
            case "all":
              this.getOrganizeUserRoot("ALL", 0, node.level, resolve)
              break
            case 'custom':
              this.getOrganizeUserRoot("CUSTOM", 0, node.level, resolve);
              break;
            case 'workGroup':
              this.getWorkGroupUser("WORK_GROUP", 0, node.level, resolve)
              break;
            case 'myWorkGroup':
              this.getWorkGroupUser("MY_WORK_GROUP", 0, node.level, resolve)
              break;
          }
        } else if (node.level >= 1) {
          switch (this.activeName) {
            case "all":
              this.getOrganizeUserRoot("ALL", node.data.origId, node.level, resolve)
              break
            case 'custom':
              this.getOrganizeUserRoot("CUSTOM", node.data.origId, node.level, resolve);
              break;
            case 'workGroup':
              this.getWorkGroupUser("WORK_GROUP", node.data.origId, node.level, resolve)
              break;
            case 'myWorkGroup':
              this.getWorkGroupUser("MY_WORK_GROUP", node.data.origId, node.level, resolve)
              break;
          }
        }
      },

      // 获取组织用户-懒加载
      getOrganizeUserRoot(queryType, parentId, level, resolve) {
        let tem = {
          queryType: queryType,
          type: this.containUser,
          parentId: parentId === undefined ? 0 : parentId,
          module: this.businessKey,
          keywords: this.searchCondition.keyword
        }
        this.API.getOrganizeLazy(tem).then(res => {
          if (res.data) {
            // console.log(2)
            res.data.map(item => {
              item.leaf = !item.subChildren
              if (level == 0) {
                this.$set(item, "expanded", true)
              }
            })
          }
          if (resolve === null) {
            if (this.searchCondition.keyword) {
              this.searchUsers = res.data
            }
          } else {
            switch (this.activeName) {
              case "all":
                if (this.temAllUsers && level === 0 && this.temAllUsers.length === 0) {
                  this.temAllUsers = (res.data)
                } else {
                  this.setTemUserChildren(this.temAllUsers, parentId, res.data)
                  // console.log(this.temAllUsers)
                }
                break
              case "custom":
                if (this.temCustomUsers && level === 0 && this.temCustomUsers.length === 0) {
                  this.temCustomUsers = (res.data)
                } else {
                  this.setTemUserChildren(this.temCustomUsers, parentId, res.data)
                }
                break
            }
            resolve(res.data)
          }
          if (level === 0) {
            this.setDefaultExpandLeftTree()
          }
          this.setDefaultCheckedData()
        })
      },

      /**
       * 描述：设置默认展开 第一级
       * 时间： 2021/3/25
       */
      setDefaultExpandLeftTree() {
        switch (this.activeName) {
          case "all":
            // console.log(this.temAllUsers, 888)
            this.setLeftExpandKeys(this.temAllUsers)
            break
          case "custom":
            this.setLeftExpandKeys(this.temCustomUsers)
            break
          case "workGroup":
            this.setLeftExpandKeys(this.temWorkGroupUsers)
            break
          case "myWorkGroup":
            this.setLeftExpandKeys(this.temMyWorkGroupUsers)
            break
        }
        this.leftDefaultExpandKeys = this.leftCacheDefaultExpandKeys
        // console.log(this.leftDefaultExpandKeys, 1)
      },

      setLeftExpandKeys(data) {
        if (data) {
          data.map(item => {
            if (item.expanded) {
              // console.log(item.id, item.expanded)
              if (!this.checkCacheExpandKeyExisted(item.id)) {
                this.leftCacheDefaultExpandKeys.push(item.id)
              }
            } else {
              if (item.children) {
                this.setLeftExpandKeys(item.children)
              }
            }
          })
        }
      },

      /**
       * 描述：检测缓存展开的key是否存在
       * 时间： 2021/3/26
       */
      checkCacheExpandKeyExisted(id) {
        let result = false
        if (this.leftCacheDefaultExpandKeys) {
          for (let item of  this.leftCacheDefaultExpandKeys) {
            if (item === id) {
              result = true
              break
            }
          }
        }
        return result
      },

      // 获取工作组用户-懒加载
      getWorkGroupUser(queryType, parentId, level, resolve) {
        // console.log("resolve",resolve)
        let tem = {
          queryType: queryType,
          type: this.containUser,
          parentId: parentId === undefined ? 0 : parentId,
          module: this.businessKey,
          keywords: this.searchCondition.keyword
        }
        this.API.getWorkGroupLazy(tem).then(res => {
          if (res.data) {
            res.data.map(item => {
              item.leaf = !item.subChildren
              if (level == 0) {
                this.$set(item, "expanded", true)
              }
            })
          }
          if (resolve === null) {
            if (this.searchCondition.keyword) {
              this.searchUsers = res.data
            }
          } else {
            switch (this.activeName) {
              case "workGroup":
                if (this.temWorkGroupUsers && level === 0 && this.temWorkGroupUsers.length === 0) {
                  this.temWorkGroupUsers = (res.data)
                } else {
                  this.setTemUserChildren(this.temWorkGroupUsers, parentId, res.data)
                }
                break
              case "myWorkGroup":
                if (this.temMyWorkGroupUsers && level === 0 && this.temMyWorkGroupUsers.length === 0) {
                  this.temMyWorkGroupUsers = (res.data)
                } else {
                  this.setTemUserChildren(this.temMyWorkGroupUsers, parentId, res.data)
                }
                break
            }
            resolve(res.data)
          }
          if (level === 0) {
            this.setDefaultExpandLeftTree()
          }
          this.setDefaultCheckedData()
        })
      },

      /**
       * 描述：设置用户树子集
       * 时间： 2021/3/24
       */
      setTemUserChildren(data, parentId, subData) {
        if (data) {
          data.map(item => {
            if (item.type === 'org' && item.origId === parentId) {
              // console.log(item.children)
              if (item.children === undefined || item.children === null) {
                this.$set(item, "children", subData)
              }
            } else {
              if (item.children) {
                this.setTemUserChildren(item.children, parentId, subData)
              }
            }
          })
        }
      },

      // 根据业务编码获取tab的控制属性
      getTabConfig() {
        if (this.businessKey === null) {
          if (this.tabConfig) {
            Object.assign(this.tabConfigData, this.tabConfig)
          }
        } else {
          this.API.getModuleSettingByKey({key: this.businessKey}).then(res => {
            Object.assign(this.tabConfigData, res.data)
            // console.log(res.data, 'data')
          })
        }
      },
      // 回显
      async updateDefaultUser() {
        console.log('回显')
        this.userNames = ''
        this.rightSelectUsers = []
        if (this.userIds) {
          let tem = {type: this.containUser, parentId: 0}
          await this.API.getOrganizeTree(tem).then(async res => {
            console.log(res.data)
            let users = this.userIds.split(',')
            if (users && res.data) {
              let otherUsers = []
              users.map((item, index) => {
                let name = this.getUserNameById(res.data, item)
                if (name === undefined || name === null) {
                  otherUsers.push(item)
                } else {
                  if (index === users.length - 1 - otherUsers.length) {
                    this.userNames += name
                  } else {
                    this.userNames += (name + ",")
                  }
                }
              })
              if (otherUsers && otherUsers.length > 0) {
                await this.getNameByGroupData(otherUsers)
              }
            }
          })
        }
      },

      getNameByGroupData(otherUsers) {
        let temGroup = {type: this.containUser, parentId: 0, isMe: 0}
        this.API.getWorkGroupTree(temGroup).then(res => {
          if (res.data) {
            otherUsers.map((item, index) => {
              let name = this.getUserNameById(res.data, item) || ""
              if (index === otherUsers.length - 1) {
                name != '' && (this.userNames += name)
              } else {
                name != '' && (this.userNames += (name + ","))
              }
            })
          }
        })
      },

      getUserNameById(data, item) {
        for (let i = 0; i < data.length; i++) {
          let user = data[i]
          if (user.id === item) {
            this.rightSelectUsers.push(user)
            return user.name
          } else {
            if (user.children !== undefined) {
              let result = this.getUserNameById(user.children, item)
              if (result) {
                return result;
              }
            } else {
              continue;
            }
          }
        }
      },
      // 右侧过滤
      rightFilter() {
        this.$refs.rightTree.filter(this.rightCondition);
      },
      // 计算选择人数
      computeCount(val) {
        let tem = val
        let users = []
        let orgs = []
        // console.log(this.totalCount,'计算',tem)
        if (tem) {
          tem.map((item) => {
            if (item.type !== 'org') {
              users.push(item)
            } else {
              orgs.push(item)
            }
          })
        }
        if (orgs) {
          orgs.map(org => {
            this.totalCount += org.userCount
          })
        }
        this.totalCount += users.length
      },
      // 右侧树点击
      nodeRightClick(data, node, self) {
        this.rightSelectNode = data
      },
      //根据类型获取图标
      icoClass(val) {
        if (val.type === 'org') {
          return "fa fa-folder";
        } else {
          return "fa fa-user";
        }
      },
      /**
       * 描述：左侧搜索-文本改变触发事件
       * 时间： 2021/3/24
       */
      searchUser() {
        this.loadNode({level: 0}, null)
      },


      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },

      /**
       * 描述：重置缓存数据
       * 时间： 2021/3/26
       */
      resetCacheData() {
        this.temAllUsers = []
        this.temCustomUsers = []
        this.temWorkGroupUsers = []
        this.temMyWorkGroupUsers = []
      },

      // tab切换
      handleClick(val) {
        this.activeName = val.name
        this.leftLazy = false
        this.setDefaultExpandLeftTree()
      },

      /**
       * 描述：获取缓存的数据选择的数组
       * 时间： 2021/3/25
       */
      setDefaultCheckedData() {
        let tem = []
        switch (this.activeName) {
          case "all":
            tem = this.getCheckedData(this.temAllUsers)
            break
          case "custom":
            tem = this.getCheckedData(this.temCustomUsers)
            break
          case "workGroup":
            tem = this.getCheckedData(this.temWorkGroupUsers)
            break
          case "myWorkGroup":
            tem = this.getCheckedData(this.temMyWorkGroupUsers)
            break
        }
        // console.log("tree_" + this.activeName, tem)
        if (this.$refs["tree_" + this.activeName]) {
          this.$refs["tree_" + this.activeName].setCheckedKeys(tem)
        }
      },

      getCheckedData(data) {
        let tem = data.flatArr()
        let result = []
        if (tem) {
          tem.map(item => {
            if (item.check) {
              result.push(item.id)
            }
          })
        }
        return result;
      },
      leftTreeNodeExpand(data, node, self) {
        if (!this.checkCacheExpandKeyExisted(data.id)) {
          this.leftCacheDefaultExpandKeys.push(data.id)
        }
        // console.log(data, node, self)
        this.leftLazy = true
        switch (this.activeName) {
          case "all":
            this.setItemExpandOrCollapse(this.temAllUsers, data, true)
            // console.log(this.temAllUsers, 999)
            break
          case "custom":
            this.setItemExpandOrCollapse(this.temCustomUsers, data, true)
            break
          case "workGroup":
            this.setItemExpandOrCollapse(this.temWorkGroupUsers, data, true)
            break
          case "myWorkGroup":
            this.setItemExpandOrCollapse(this.temMyWorkGroupUsers, data, true)
            break
        }
      },
      leftTreeNodeCollapse(data, node, self) {
        // console.log(data, node, self)
        let index = this.leftCacheDefaultExpandKeys.findIndex((item) => {
          return item === data.id
        })
        if (index != -1) {
          this.leftCacheDefaultExpandKeys.splice(index, 1)
        }
        switch (this.activeName) {
          case "all":
            this.setItemExpandOrCollapse(this.temAllUsers, data, false)
            break
          case "custom":
            this.setItemExpandOrCollapse(this.temCustomUsers, data, false)
            break
          case "workGroup":
            this.setItemExpandOrCollapse(this.temWorkGroupUsers, data, false)
            break
          case "myWorkGroup":
            this.setItemExpandOrCollapse(this.temMyWorkGroupUsers, data, false)
            break
        }
      },

      /**
       * 描述：设置item的展开，闭合属性
       * 时间： 2021/3/26
       */
      setItemExpandOrCollapse(data, item, expand) {
        if (data) {
          for (let model of data) {
            if (model.id === item.id) {
              if (model.expanded) {
                model.expanded = expand
              } else {
                this.$set(model, "expanded", expand)
              }
            } else {
              if (model.children) {
                this.setItemExpandOrCollapse(model.children, item, expand)
              }
            }
          }
        }
      },

      // 左-树点击事件
      nodeClick(data, node, self) {
        this.leftSelectNode = data
      },
      //左侧多选事件
      leftCheckChange(data, self, node) {
        // console.log(data, self, node)
        this.setLeftTemTreeCheckedUserByActive(data, self)
        //如果取消选择，右侧去掉相关数据
        if (!self) {
          this.rightSelectUsers.map((rightUser, index) => {
            if (rightUser.id === data.id) {
              this.rightSelectUsers.splice(index, 1)
            }
          })
        }
        let temRightUsers = _.cloneDeep(this.rightSelectUsers)
        // console.log(this.$refs["tree_" + this.activeName].getCheckedNodes(),this.temAllUsers)
        this.$refs["tree_" + this.activeName].getCheckedNodes().map(item => {
          if (temRightUsers) {
            let existed = false
            temRightUsers.map((rightUser) => {
              if (rightUser.id === item.id) {
                existed = true
              }
            })
            if (!existed) {
              if (item.id===data.id) {
                temRightUsers.push(data) // 重新给children 赋值的数据
              }else {
                temRightUsers.push(item)
              }
            }
          }
        })
        let depts = []
        // 右侧数据在去重复一次
        temRightUsers.map(item => {
          if (item.type !== 'user') {
            depts.push(item)
          }
        })
        let result = []
        temRightUsers.map((item, index) => {
          // console.log(index,item.id)
          let existed = false
          if (depts) {
            for (let dept of depts) {
              if (dept.children) {
                existed = this.removeExistedDeptAndUser(dept.children, item)
                if (existed) {
                  return
                }
              }
            }
          }
          if (!existed) {
            result.push(item)
          }
        })
        this.rightSelectUsers = _.cloneDeep(result)
        // console.log( this.rightSelectUsers )
      },

      /**
      * 描述：清除某一项数据的check状态
      * 时间： 2021/3/26
      */
      clearItemCheck(item, check) {
        let tem =[].concat(this.temAllUsers,this.temCustomUsers,this.temWorkGroupUsers,this.temMyWorkGroupUsers)
        // console.log(tem,item,'090')
        this.setLeftTemTreeCheckedUserClear(tem, item, check)
        this.setDefaultCheckedData()
      },

      setLeftTemTreeCheckedUserClear(data, item, check) {
        if (data) {
          for (let model of  data) {
            if (model.id === item.id) {
              if (model.check) {
                console.log(model.name)
                model.check = check
                break
              }
            } else {
              if (model.children) {
                this.setLeftTemTreeCheckedUser(model.children, item, check)
              }
            }
          }
        }
      },

      /**
      * 描述：如果删除的是部门，把部门子集的所有数据
      * 时间： 2021/3/26
      */
      cancelAllSubCheck() {

      },

      /**
       * 描述：左侧树缓存数据增加checked 字段，便于切换时回显
       * @param item 操作的item
       * @param check 选中状态true 选中，false取消选中
       * 时间： 2021/3/25
       */
      setLeftTemTreeCheckedUserByActive(item, check) {
        switch (this.activeName) {
          case "all":
            this.setLeftTemTreeCheckedUser(this.temAllUsers, item, check)
            break
          case "custom":
            this.setLeftTemTreeCheckedUser(this.temCustomUsers, item, check)
            break
          case "workGroup":
            this.setLeftTemTreeCheckedUser(this.temWorkGroupUsers, item, check)
            break
          case "myWorkGroup":
            this.setLeftTemTreeCheckedUser(this.temMyWorkGroupUsers, item, check)
            break
        }
      },

      /**
       * 描述：左侧树缓存数据增加checked 字段，便于切换时回显
       * @param data 数据集
       * @param item 操作的item
       * @param check 选中状态true 选中，false取消选中
       * 时间： 2021/3/25
       */
      setLeftTemTreeCheckedUser(data, item, check) {
        if (data) {
          for (let model of  data) {
            if (model.id === item.id) {
              if (model.check) {
                model.check = check
                if (model.type!=='user') {
                  item.children = model.children
                }
              } else {
                this.$set(model, "check", check)
              }
              break
            } else {
              if (model.children) {
                this.setLeftTemTreeCheckedUser(model.children, item, check)
              }
            }
          }
        }
      },

      // 递归遍历右侧选择的用户和部门以及部门下的子集，去除重复数据
      removeExistedDeptAndUser(data, item) {
        let existed = false
        if (data) {
          // map 遍历不能跳出，es6 退出for of 可以退出循环
          for (let rightUser of data) {
            if (rightUser.id === item.id) {
              existed = true
              break
            } else {
              if (rightUser.children) {
                existed = this.removeExistedDeptAndUser(rightUser.children, item)
              }
            }
          }
        }
        return existed
      },
      // 展示用户弹出
      showUserDialog() {
        this.sortDialogVisible = true;
        this.resetCacheData()
        this.leftDefaultExpandKeys = []
        if (this.userIds===''){
          this.rightSelectUsers = []
        }
      },
      // 全选
      allSelect() {
        if (this.containUser === 0) {
          switch (this.activeName) {
            case "all":
              this.rightSelectUsers .push(this.temAllUsers)
              break
            case "custom":
              this.rightSelectUsers.push(this.temCustomUsers)
              break
            case "workGroup":
              this.rightSelectUsers.push(this.temWorkGroupUsers)
              break
            case "myWorkGroup":
              this.rightSelectUsers.push(this.temMyWorkGroupUsers)
              break
          }
        }
      },
      // 清空
      clearSelect() {
        this.rightSelectUsers = []
        this.clearTemChecked(this.temAllUsers)
        this.clearTemChecked(this.temCustomUsers)
        this.clearTemChecked(this.temWorkGroupUsers)
        this.clearTemChecked(this.temMyWorkGroupUsers)
        this.setDefaultCheckedData()
      },

      /**
      * 描述：清空缓存数组数据的选择状态
      * 时间： 2021/3/26
      */
      clearTemChecked(data) {
         if (data){
           data.map(item=>{
             item.check =false
             if (item.children){
               this.clearTemChecked(item.children)
             }
           })
         }
      },

      // 确认选择的用户
      confirmSelectUser() {
        if (this.leftSelectNode) {
          if (this.selectType === 1 && this.leftSelectNode.type !== 'user') {
            this.warning("只能选择用户")
            return
          }
          if (this.selectType === 2 && this.leftSelectNode.type === 'user') {
            this.warning("请选择工作组或机构")
            return
          }
          if (!this.isMulSelect && this.rightSelectUsers.length > 0) {
            this.warning("只允许选择一个用户")
            return
          }
          // console.log(this.leftSelectNode)
          let i = this.rightSelectUsers.findIndex(item=>{
            return item.id=== this.leftSelectNode.id
          })
          // console.log(i)
          if (i !== -1) {
            this.warning(this.leftSelectNode.name + ",已存在相同数据")
          } else {

            this.rightSelectUsers.push(this.leftSelectNode);
            this.leftSelectNode = null
          }
        }
      },
      // 删除选择的用户
      delSelectUser() {
        if (this.rightSelectNode) {
          let i = this.rightSelectUsers.findIndex(item=>{
            return item.id===this.rightSelectNode.id
          })
          this.rightSelectUsers.splice(i, 1);
          this.clearItemCheck(this.rightSelectNode,false)
          this.rightSelectNode = null;
          // console.log(this.temAllUsers)
        }
      },

      // 跟新组件值
      async updateUsers() {
        let val = ''
        let userIds = ''
        this.userNames = ''
        this.origId = ''
        let deptNames = ''
        if (this.rightSelectUsers) {
          this.rightSelectUsers.map((item, index) => {
            if (index === this.rightSelectUsers.length - 1) {
              this.userNames += item.name
              val += item.id
              userIds += item.id
              deptNames += item.deptName
              this.origId += item.origId
            } else {
              this.userNames += (item.name + ",")
              val += (item.id + ",")
              userIds += (item.id + ",")
              deptNames += (item.deptName + ",")
              this.origId += (item.origId + ',')
            }
          })
        }
        console.log(val, this.userNames)
        this.isLoad = false
        this.$emit('input', val)
        let obj = {}
        obj.origId = this.origId;
        obj.userNames = this.userNames;
        obj.deptNames = deptNames;
        obj.uuid = val
        this.$emit('getUser', obj)
        this.sortDialogVisible = false
        await this.funcSubmit(obj);
      }
    }
  };
</script>

<style lang="less" scoped>
  .flex_box {
    display: table-cell;
    vertical-align: middle;
  }

</style>
